package cn.edu.swu.io;

import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {
    public static void saveImage(String url,String savePath) throws IOException{

        ensureDirectoryExists(getDirectoryFromPath(savePath));

        URL imageUrl = new URL(url);
        try (InputStream in = imageUrl.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        appendLog("Downloaded: " + url + " -> " + savePath);
    }
    public static void ensureDirectoryExists(String dirPath) {
        try {
            Files.createDirectories(Paths.get(dirPath));
        } catch (IOException e) {
            System.err.println("创建目录失败: " + dirPath + " - " + e.getMessage());

        }
    }

    public static void appendLog(String log) {

        String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String logEntry = timestamp + " " + log;

        try (FileWriter fw = new FileWriter("download_log.txt", true);
             BufferedWriter bw = new BufferedWriter(fw)) {

            bw.write(logEntry);
            bw.newLine();

        } catch (IOException e) {
            System.err.println("写入日志文件失败: " + e.getMessage());
        }
    }

    private static String getDirectoryFromPath(String filePath) {
        return new File(filePath).getParent();
    }
}
